#include "client.h"

#define BUFFER_SIZE 4096

void main(int argc, char* argv[])
{
	char* serverName = (argc > 1) ? argv[1] : "192.168.1.103";
	SOCKET connSocket = initClient(serverName);
	int bytesSent = 0, bytesRecv = 0;
    char recvBuff[BUFFER_SIZE];
	int i = 1;
	//char message[4096] = "PUT /index2.html HTTP/1.1\r\nHost: lar?\r\nContent-Length: 24\r\n\r\n<html>Hello World</html>";
	//char message[4096] = "DELETE /index.html HTTP/1.1\r\nHost: lar?\r\n\r\n";
	//char message[4096] = "GET /index.html HTTP/1.1\r\nHost: lar?\r\n\r\n";
	///char message[4096] = "PUT /index2.html HTTP/1.1\r\nHost: localhost\r\nAccept: */*\r\nContent-Length:12\r\n\r\nTroLOLOLOLOL";
	//char message[4096] = "TRACE / HTTP/1.1\r\nHost: lar?\r\nContent-Length: 0\r\n\r\n";
	char message[4096] = "HEAD /index.html HTTP/1.1\r\nHost: lar?\r\nContent-Length: 0\r\n\r\n";
	int len = strlen(message);

	while (i > 0)
	{
		cout<<"Sending....\n";
		bytesSent = send(connSocket, message, len, 0);
		if (bytesSent == SOCKET_ERROR)
		{
			cout << "HTTP Client: Error at send(): " << WSAGetLastError() << endl;
			closesocket(connSocket);
			WSACleanup();
			return;
		}
		cout<<"HTTP Client: Sent: "<<bytesSent<<" bytes of \n--BEGINNING OF MESSAGE--\n" << message << "\n--END OF MESSAGE---\n";


		cout<<"Receiving....\n";
		bytesRecv = recv(connSocket, recvBuff, BUFFER_SIZE , 0);
		if (bytesRecv == SOCKET_ERROR)
		{
			cout << "HTTP Client: Error at recv(): " << WSAGetLastError() << endl;
			closesocket(connSocket);
			WSACleanup();
			return;
		}

		if (bytesRecv == 0)
		{
			cout<<"Server closed the connection\n";
			return;
		}

		recvBuff[bytesRecv]='\0'; //add the null-terminating to make it a string
		cout<<"HTTP Client: Recieved: "<<bytesRecv<<" bytes of \n--BEGINNING OF MESSAGE--\n" << recvBuff << "--END OF MESSAGE---\n";
		i--;
	}
	char bla;
	cin >> bla;
	closesocket(connSocket);
	WSACleanup();
}

SOCKET initClient(char* i_ServerName)
{
	WSAData wsaData;
	if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
	{
		cout << "HTTP Client: Error at WSAStartup()\n";
		exit(1);
	}

    SOCKET connSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (connSocket == INVALID_SOCKET)
	{
        cout << "HTTP Client: Error at socket(): " << WSAGetLastError() << endl;
        WSACleanup();
        exit(1);
	}

	sockaddr_in server;
    server.sin_family = AF_INET; 
	server.sin_addr.s_addr = inet_addr(i_ServerName);
	server.sin_port = htons(HTTP_PORT);

	if (connect(connSocket, (SOCKADDR *) &server, sizeof(server)) == SOCKET_ERROR)
	{
		cout << "HTTP Client: Error at connect(): " << WSAGetLastError() << endl;
        closesocket(connSocket);
		WSACleanup();
        exit(1);
    }

	return connSocket;
}